﻿using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Internal;
using SmartConference.Domain;
using SmartConference.Domain.Logs;
using System.Reflection.Metadata;

namespace SmartConference.Infrastructure
{
    public class SmartConferenceDbContext : DbContext
    {
        public SmartConferenceDbContext(DbContextOptions options) : base(options)
        {
        }
        public DbSet<UserInfo> UserInfos { get; set;}
        public DbSet<UserRole> UserRoles { get; set; }
        public DbSet<RoleInfo> RoleInfos { get; set; }
        public DbSet<RolePermission> RolePermissions { get; set; }
        public DbSet<PermissionInfo> PermissionInfos { get; set; }
        public DbSet<DepartmentInfo> DepartmentInfos { get; set; }
        public DbSet<MeetingReservation> MeetingReservations { get; set; }
        public DbSet<MeetingApprove> MeetingApprovals { get; set; }
        public DbSet<MeetingRoom> MeetingRooms { get; set; }
        //public DbSet<ApprovalLog> ApprovalLogs { get; set; }
        //public DbSet<LoginLog> LoginLogs { get; set; }
        //public DbSet<OperationLog> OperationLogs { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<UserInfo>().ToTable("UserInfo");
            modelBuilder.Entity<UserInfo>().HasKey(x => x.IDNumber);
            modelBuilder.Entity<UserInfo>().Property(x => x.UserNumber).IsRequired().HasMaxLength(50);
            modelBuilder.Entity<UserInfo>().Property(x => x.PhoneNumber).IsRequired().HasMaxLength(11);
            modelBuilder.Entity<UserInfo>().Property(x => x.UserPassword).IsRequired().HasMaxLength(50);
            modelBuilder.Entity<UserInfo>().Property(x => x.MemberLevel).IsRequired().HasMaxLength(50);
            modelBuilder.Entity<UserInfo>().Property(x => x.Sex).IsRequired();
            modelBuilder.Entity<UserInfo>().Property(x => x.Birthday).IsRequired();
            modelBuilder.Entity<UserInfo>().Property(x => x.LiveCity).IsRequired().HasMaxLength(50);
            modelBuilder.Entity<UserInfo>().Property(x => x.Occupation).IsRequired().HasMaxLength(50);
            modelBuilder.Entity<UserInfo>().Property(x => x.PersonalizedDesc).IsRequired().HasMaxLength(50);
            modelBuilder.Entity<UserInfo>().Property(x => x.UserStatus).IsRequired();
            modelBuilder.Entity<UserInfo>().Property(x => x.OrderList).IsRequired();
            modelBuilder.Entity<UserInfo>().Property(x => x.ConsumptionSum).IsRequired();
            modelBuilder.Entity<UserInfo>().Property(x => x.AvailableIntegral).IsRequired();

            //// <summary>
            /// 数据播种初始化用户信息
            /// </summary>
            modelBuilder.Entity<UserInfo>().HasData(
                new UserInfo()
                {
                    IDNumber = 1,
                    UserNumber = "admin",
                    PhoneNumber = "12345678901",
                    UserPassword = "123456",
                    MemberLevel = "管理员",
                    Sex = 1,
                    Birthday = DateTime.Now,
                    LiveCity = "上海",
                    Occupation = "程序员",
                    PersonalizedDesc = "程序员",
                    UserStatus = UserStatus.Enable,
                    OrderList = 1,
                    ConsumptionSum = 100,
                    AvailableIntegral = 100,
                    CreateId = 1,
                    CreateName = "admin",
            }   );



                // 自动为所有继承自 BaseEntity 的实体加上 IsDelete == false 的全局过滤器
                foreach (var entityType in modelBuilder.Model.GetEntityTypes())
                // 判断是否继承自 BaseEntity，且不是抽象类
                if
                (typeof(BaseEntity).IsAssignableFrom(entityType.ClrType) && !entityType.ClrType.IsAbstract)
                {
                    //构建表达式x=>!x.IsDelete
                    //创建一个参数 x，类型为当前实体类型(如 User、Role 等)。
                    var parameter = System.Linq.Expressions.Expression.Parameter(entityType.ClrType,
                    "x");
                    //获取当前实体类型的 IsDelete 属性。
                    var property = System.Linq.Expressions.Expression.Property(parameter, nameof
                    (BaseEntity.IsDelete));
                    //创建一个表达式，表示 IsDelete 属性等于 false。
                    var compare = System.Linq.Expressions.Expression.Equal(property,
                    System.Linq.Expressions.Expression.Constant(false));
                    //创建一个 Lambda 表达式，表示x=>!x.IsDelete。
                    var lambda = System.Linq.Expressions.Expression.Lambda(compare,
                    parameter);
                    //将这个 Lambda 表达式作为査询过滤器应用到当前实体类型上。
                    entityType.SetQueryFilter(lambda);
                }

        }

        /// <summary>
        /// 重写SaveChanges方法
        /// </summary>
        /// <returns></returns>
        public override int SaveChanges()
        {
            var entries = ChangeTracker.Entries<BaseEntity>();
            foreach (var entry in entries)
            {
                if (entry.State == EntityState.Added)
                {
                    entry.Entity.CreateTime = DateTime.Now;
                    entry.Entity.CreateId = 1; // TODO: 获取当前用户ID
                    entry.Entity.CreateName = "Admin"; // TODO: 获取当前用户名
                }
                else if (entry.State == EntityState.Modified)
                {
                    entry.Entity.UpdateTime = DateTime.Now;
                    entry.Entity.UpdateId = 1; // TODO: 获取当前用户ID
                    entry.Entity.UpdateName = "Admin"; // TODO: 获取当前用户名
                }
                else if (entry.State == EntityState.Deleted)
                {
                    entry.Entity.DeleteTime = DateTime.Now;
                    entry.Entity.DeleteId = 1; // TODO: 获取当前用户ID
                    entry.Entity.DeleteName = "Admin"; // TODO: 获取当前用户名
                    entry.Entity.IsDelete = true;
                    entry.State = EntityState.Modified;
                }
            }


            return base.SaveChanges();
        }
    }
}
